package cn.iocoder.yudao.module.wine.service.businessuser;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.MPJLambdaWrapperX;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.member.controller.admin.user.vo.MemberUserUpdateReqVO;
import cn.iocoder.yudao.module.member.controller.app.auth.vo.AppAuthSmsSendReqVO;
import cn.iocoder.yudao.module.member.convert.auth.AuthConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.dal.mysql.user.MemberUserMapper;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi;
import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeUseReqDTO;
import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeValidateReqDTO;
import cn.iocoder.yudao.module.system.enums.sms.SmsSceneEnum;
import cn.iocoder.yudao.module.trade.api.brokerage.BrokerageUserApi;
import cn.iocoder.yudao.module.trade.api.brokerage.dto.BrokerageUserDTO;
import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageUserDO;
import cn.iocoder.yudao.module.wine.api.WineConfigApi;
import cn.iocoder.yudao.module.wine.api.dto.BusinessUserDTO;
import cn.iocoder.yudao.module.wine.api.dto.WineConfigDTO;
import cn.iocoder.yudao.module.wine.controller.app.businessuser.vo.*;
import cn.iocoder.yudao.module.wine.dal.dataobject.businesscredit.BusinessCreditDO;
import cn.iocoder.yudao.module.wine.dal.dataobject.businessuserlog.BusinessUserLogDO;
import cn.iocoder.yudao.module.wine.dal.dataobject.memberdeadline.MemberDeadlineDO;
import cn.iocoder.yudao.module.wine.dal.dataobject.membertype.MemberTypeDO;
import cn.iocoder.yudao.module.wine.dal.dataobject.uservisitor.UserVisitorDO;
import cn.iocoder.yudao.module.wine.dal.mysql.businessuserlog.BusinessUserLogMapper;
import cn.iocoder.yudao.module.wine.enums.BusinessUserEnum;
import cn.iocoder.yudao.module.wine.service.uservisitor.UserVisitorService;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Collection;
import java.util.List;

import cn.iocoder.yudao.module.wine.controller.admin.businessuser.vo.*;
import cn.iocoder.yudao.module.wine.dal.dataobject.businessuser.BusinessUserDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.wine.dal.mysql.businessuser.BusinessUserMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getTerminal;
import static cn.iocoder.yudao.module.wine.enums.ErrorCodeConstants.*;

/**
 * 商家配置 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class BusinessUserServiceImpl implements BusinessUserService {

    //region 代码块
    @Resource
    private BusinessUserMapper businessUserMapper;

    @Resource
    private BrokerageUserApi brokerageUserApi;

    @Resource
    private MemberUserMapper memberUserMapper;

    @Resource
    private MemberUserService memberUserService;

    @Resource
    private BusinessUserLogMapper businessUserLogMapper;

    @Resource
    private SmsCodeApi smsCodeApi;

    @Resource
    private UserVisitorService userVisitorService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private DictDataApi dataApi;

    @Resource
    private WineConfigApi wineConfigApi;

    /**
     * 发布信息默认条数
     */
    @Value("${wine.business-default-number}")
    private String businessDefaultNumber;
    /**
     * 默认信用分
     */
    @Value("${wine.credit-score}")
    private String creditScore;
    //endregion

    /**
     * 后台手动创建商家(暂无功能)
     * @param createReqVO 创建信息
     * @return
     */
    @Override
    public Long createBusinessUser(BusinessUserSaveReqVO createReqVO) {
        //1.创建用户
        //TODO: 创建用户账户........
        //2.插入商家
        BusinessUserDO businessUser = BeanUtils.toBean(createReqVO, BusinessUserDO.class);
        //自营商家
        businessUser.setIsSelfSupport(BusinessUserEnum.IS_SELF_SUPPORT.getCode());
        //入驻商家--1,认证商家--2,商家团长--3,个人团长--4，保证金用户--5
        businessUser.setCreditId(1);

        businessUserMapper.insert(businessUser);
        // 返回
        return businessUser.getId();
    }

    /**
     * 管理员创建个人团长
     * @param createReqVO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer createTeamUser(TeamUserSaveReqVO createReqVO) {

        //1.注册用户账号
        MemberUserDO user = memberUserService.createTeamUser(createReqVO.getMobile(), createReqVO.getNickname(),
                createReqVO.getName(), createReqVO.getPassword(), createReqVO.getAreaId(),
                createReqVO.getAvatar(), createReqVO.getSex(),createReqVO.getMark(),createReqVO.getTeamAudit());
        //2.创建商家信息(酒类模块商家表)
        if(user!=null) {

            BusinessUserDO businessUserDTO = BeanUtils.toBean(createReqVO, BusinessUserDO.class);

            LocalDateTime now = LocalDateTime.now();
            Integer profitYear = 1; //默认一年
            //如果开启免费，则增加免费使用时间
            WineConfigDTO wineConfigDTO = wineConfigApi.getWineConfigInfo();
            if (wineConfigDTO != null && wineConfigDTO.getIsOpenMonth() > 0 && wineConfigDTO.getFreeMonth() > 0) {
                profitYear = wineConfigDTO.getProfitYear();
                LocalDateTime expirationTime = now.plusMonths(wineConfigDTO.getFreeMonth());
                businessUserDTO.setExpirationTime(expirationTime);
            }
            //审核则增加默认使用时间
            if (createReqVO.getTeamAudit() == 2) {
                LocalDateTime overTime = now.plusYears(profitYear);
                businessUserDTO.setOpenTime(now);
                businessUserDTO.setOverTime(overTime);
            }

            BrokerageUserDTO dto = new BrokerageUserDTO();
            dto.setId(user.getId());
            dto.setBindUserId(0L);
            dto.setBrokerageEnabled(true);
            dto.setBusinessType(0);
            dto.setUserBusiness(0);
            dto.setBusinessStartTime(now);
            dto.setBusinessEndTime(now);
            dto.setTeamType(1);
            dto.setUserTeam(0);
            dto.setTeamStartTime(now);
            dto.setTeamEndTime(now);
            //创建佣金账户
            brokerageUserApi.addBrokerageUser(dto);

            businessUserDTO.setUserId(user.getId());
            businessUserDTO.setMemberTypeId(0L);
            //入驻商家--1,认证商家--2,商家团长--3,个人团长--4，保证金用户--5
            businessUserDTO.setCreditId(4);
            businessUserDTO.setCreditScore(0);
            //个人团长没有发布功能
            businessUserDTO.setBuyNum(0);
            businessUserDTO.setComplainNum(0);
            businessUserDTO.setSupplyNum(0);
            businessUserDTO.setLeaveNum(0);
            businessUserDTO.setStatus(BusinessUserEnum.APPLYING_STATUS.getCode());
            businessUserDTO.setIsAuth(BusinessUserEnum.AUTHENTICATED_AUTH.getCode());
            businessUserDTO.setIsSelfSupport(BusinessUserEnum.NOT_SELF_SUPPORT.getCode());

            return businessUserMapper.insert(businessUserDTO);
        }
        return 0;
    }

    /**
     * 更新商家信息
     * @param updateReqVO 更新信息
     */
    @Override
    public void updateBusinessUser(BusinessUserSaveReqVO updateReqVO) {
        // 校验存在
        validateBusinessUserExists(updateReqVO.getId());
        // 更新
        BusinessUserDO updateObj = BeanUtils.toBean(updateReqVO, BusinessUserDO.class);

        businessUserMapper.updateById(updateObj);
    }

    @Override
    public void deleteBusinessUser(Long id) {
        // 校验存在
        validateBusinessUserExists(id);
        // 删除
        businessUserMapper.deleteById(id);
    }

    private BusinessUserDO validateBusinessUserExists(Long id) {
        BusinessUserDO businessUserDO = businessUserMapper.selectById(id);
        if (businessUserDO == null) {
            throw exception(INFO_NOT_EXISTS);
        } else {
            return businessUserDO;
        }
    }

    @Override
    public BusinessUserRespVO getBusinessUser(Long id) {
        return businessUserMapper.selectJoinOne(BusinessUserRespVO.class, new MPJLambdaWrapperX<BusinessUserDO>()
                .selectAll(BusinessUserDO.class)
                .selectAs(BusinessCreditDO::getName, "creditName")
                .selectAs(MemberUserDO::getMobile,BusinessUserRespVO::getMobile)
                .selectAs(MemberUserDO::getName,BusinessUserRespVO::getUsername)
                .selectAs(MemberUserDO::getNickname,BusinessUserRespVO::getNickname)
                .leftJoin(BusinessCreditDO.class, BusinessCreditDO::getId, BusinessUserDO::getCreditId)
                .leftJoin(MemberUserDO.class,MemberUserDO::getId,BusinessUserDO::getUserId)
                .eq(BusinessUserDO::getId, id)
        );
    }

    @Override
    public PageResult<BusinessUserRespVO> getBusinessUserPage(BusinessUserPageReqVO pageReqVO) {
        return businessUserMapper.selectPage(pageReqVO);
    }


    @Override
    public void sendSmsCode(RegisterSmsSendReqVO reqVO) {
        Integer scene = SmsSceneEnum.MEMBER_LOGIN.getScene();
        AppAuthSmsSendReqVO appAuthSmsSendReqVO = new AppAuthSmsSendReqVO();
        appAuthSmsSendReqVO.setMobile(reqVO.getMobile());
        appAuthSmsSendReqVO.setScene(scene);
        // 执行发送
        smsCodeApi.sendSmsCode(AuthConvert.INSTANCE.convert(appAuthSmsSendReqVO).setCreateIp(getClientIP()));
    }

    @Override
    public void validateSmsCode(Long loginUserId, RegisterSmsSendReqVO reqVO) {
        Integer scene = SmsSceneEnum.MEMBER_LOGIN.getScene();
        SmsCodeValidateReqDTO smsCodeValidateReqDTO = new SmsCodeValidateReqDTO();
        smsCodeValidateReqDTO.setMobile(reqVO.getMobile());
        smsCodeValidateReqDTO.setCode(reqVO.getCode());
        smsCodeValidateReqDTO.setScene(scene);
        smsCodeApi.validateSmsCode(smsCodeValidateReqDTO);
    }


    @Override
    public BusinessUserRespVO appGetBusinessUser(Long id) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        if (loginUserId != null) {
            if (!loginUserId.equals(id)) {
                //他人访问个人信息,添加访客记录
                UserVisitorDO userVisitorDO = new UserVisitorDO();
                userVisitorDO.setUserId(id);
                userVisitorDO.setVisitorId(loginUserId);
                userVisitorDO.setAccessTime(LocalDateTime.now());
                userVisitorService.addUserVisitorRecord(userVisitorDO);
            }
        }
        BusinessUserRespVO businessUserRespVO = businessUserMapper.selectJoinOne(BusinessUserRespVO.class, new MPJLambdaWrapperX<BusinessUserDO>()
                .eq(BusinessUserDO::getUserId, id)
                .leftJoin(BusinessCreditDO.class, BusinessCreditDO::getId, BusinessUserDO::getCreditId)
                .leftJoin(MemberUserDO.class, MemberUserDO::getId, BusinessUserDO::getUserId)
                .leftJoin(MemberDeadlineDO.class, MemberDeadlineDO::getUserId, BusinessUserDO::getUserId)
                .leftJoin(MemberTypeDO.class, MemberTypeDO::getId, BusinessUserDO::getMemberTypeId)
                .selectAll(BusinessUserDO.class)

                .selectAs(BusinessCreditDO::getId, BusinessUserRespVO::getCreditId)
                .selectAs(BusinessCreditDO::getName, BusinessUserRespVO::getCreditName)

                .selectAs(MemberDeadlineDO::getStartDate, BusinessUserRespVO::getStartDate)
                .selectAs(MemberDeadlineDO::getEndDate, BusinessUserRespVO::getEndDate)

                .selectAs(MemberTypeDO::getId, BusinessUserRespVO::getMemberTypeId)

                .selectAs(MemberUserDO::getMobile, BusinessUserRespVO::getMobile)
                .selectAs(MemberUserDO::getIsTeam, BusinessUserRespVO::getIsTeam)
                .selectAs(MemberUserDO::getIsBusiness, BusinessUserRespVO::getIsBusiness)
                .selectAs(MemberUserDO::getTeamAudit, BusinessUserRespVO::getTeamAudit)
                .selectAs(MemberUserDO::getNickname, BusinessUserRespVO::getNickname)
                .selectAs(MemberUserDO::getName, BusinessUserRespVO::getRealName)
                .selectAs(MemberUserDO::getMark, BusinessUserRespVO::getMark)
                .selectAs(MemberUserDO::getAvatar, BusinessUserRespVO::getAvatar)
                .selectAs(MemberUserDO::getMoneyReceivingCode, BusinessUserRespVO::getMoneyReceivingCode)
                .selectAs(MemberUserDO::getTeamOpenTime, BusinessUserRespVO::getTeamOpenTime)
                .selectAs(MemberUserDO::getTeamOverTime, BusinessUserRespVO::getTeamOverTime)
                .selectAs(MemberUserDO::getSex, BusinessUserRespVO::getSex)
        );
        if (businessUserRespVO != null) {
            businessUserRespVO.setStartDateTime(businessUserRespVO.getStartDate() == null ? null : businessUserRespVO.getStartDate().atTime(LocalTime.of(0, 0)));
            businessUserRespVO.setEndDateTime(businessUserRespVO.getEndDate() == null ? null : businessUserRespVO.getEndDate().atTime(LocalTime.of(0, 0)));
        }
        return businessUserRespVO;
    }

    @Override
    public Integer updatePassword(AppUserUpdatePasswordVO passwordVO) {
        if (!passwordVO.getConfirmPassword().equals(passwordVO.getPassword())) {
            throw exception(PASSWORD_NOT_EQUAL);
        }
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        MemberUserDO user = memberUserService.getUser(loginUserId);
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }
        String encode = passwordEncoder.encode(passwordVO.getPassword());
        String password = user.getPassword();
        if (encode.equals(password)) {
            throw exception(OLD_NEW_PASSWORD_EQUAL);
        }
        user.setPassword(encode);
        return memberUserService.updateAppPassword(user);
    }

    /**
     * 后台 审核商家
     * @param updateReqVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditBusinessUser(BusinessUserSaveReqVO updateReqVO) {
        BusinessUserDO businessUserDO = validateBusinessUserExists(updateReqVO.getId());
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (loginUser == null) {
            throw exception(LOGIN_USER_NOT_EXISTS);
        }
        //商家认证
        Integer isAuth = updateReqVO.getIsAuth();
        if (!isAuth.equals(businessUserDO.getIsAuth())) {
            BusinessUserLogDO businessUserLogDO = new BusinessUserLogDO();
            //商家认证字典
            List<DictDataRespDTO> merchantCertification = dataApi.getDictDataList("merchant_certification");
            if (merchantCertification == null || merchantCertification.size() == 0) {
                throw exception(DICT_DATA_NOT_EXISTS);
            }
            businessUserLogDO.setUserId(loginUser.getId());
            for (int i = 0; i < merchantCertification.size(); i++) {
                DictDataRespDTO dictDataRespDTO = merchantCertification.get(i);
                if (dictDataRespDTO.getValue().equals(String.valueOf(businessUserDO.getIsAuth()))) {
                    businessUserLogDO.setBeforeStatus(dictDataRespDTO.getLabel());
                }
                if (dictDataRespDTO.getValue().equals(String.valueOf(isAuth))) {
                    businessUserLogDO.setAfterStatus(dictDataRespDTO.getLabel());
                }
            }
            Integer userType = loginUser.getUserType();
            if (UserTypeEnum.ADMIN.getValue().equals(userType)) {
                businessUserLogDO.setContent(UserTypeEnum.ADMIN.getName() + "审核商家认证：" + businessUserLogDO.getBeforeStatus() + "->" + businessUserLogDO.getAfterStatus());
            }
            businessUserLogDO.setAppUserId(businessUserDO.getUserId());
            businessUserLogMapper.insert(businessUserLogDO);
        }
        //商家审核
        Integer status = updateReqVO.getStatus();
        if (!status.equals(businessUserDO.getStatus())) {
            //商家状态字典
            List<DictDataRespDTO> merchantStatus = dataApi.getDictDataList("merchant_status");
            if (merchantStatus == null || merchantStatus.size() == 0) {
                throw exception(DICT_DATA_NOT_EXISTS);
            }
            BusinessUserLogDO businessUserLogDO = new BusinessUserLogDO();
            businessUserLogDO.setUserId(loginUser.getId());
            for (int i = 0; i < merchantStatus.size(); i++) {
                DictDataRespDTO dictDataRespDTO = merchantStatus.get(i);
                if (dictDataRespDTO.getValue().equals(String.valueOf(businessUserDO.getStatus()))) {
                    businessUserLogDO.setBeforeStatus(dictDataRespDTO.getLabel());
                }
                if (dictDataRespDTO.getValue().equals(String.valueOf(status))) {
                    businessUserLogDO.setAfterStatus(dictDataRespDTO.getLabel());
                }
            }
            Integer userType = loginUser.getUserType();
            if (UserTypeEnum.ADMIN.getValue().equals(userType)) {
                businessUserLogDO.setContent("id = " + loginUser.getId() + "的" + UserTypeEnum.ADMIN.getName() + "修改商家状态：" + businessUserLogDO.getBeforeStatus() + "->" + businessUserLogDO.getAfterStatus());
            }
            businessUserLogDO.setAppUserId(businessUserDO.getUserId());
            businessUserLogMapper.insert(businessUserLogDO);
            //如果是审核
            //if(BusinessUserEnum.AUDITED_STATUS.getCode().equals(status)){
            //}
        }

        BusinessUserDO bean = BeanUtils.toBean(updateReqVO, BusinessUserDO.class);

        businessUserMapper.updateById(bean);
    }


    /**
     * 商家入驻，并可绑定上下级关系（添加和修改共用一个方法）
     * @param createReqVO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer appCreateBusinessUser(AppBusinessUserSaveReqVO createReqVO) {
        // 校验验证码
        if (StringUtil.isNotBlank(createReqVO.getCode())) {
            Integer scene = SmsSceneEnum.MEMBER_LOGIN.getScene();
            SmsCodeUseReqDTO smsCodeUseReqDTO = new SmsCodeUseReqDTO();
            smsCodeUseReqDTO.setCode(createReqVO.getCode());
            smsCodeUseReqDTO.setMobile(createReqVO.getMobile());
            smsCodeUseReqDTO.setUsedIp(getClientIP());
            smsCodeUseReqDTO.setScene(scene);
            smsCodeApi.useSmsCode(smsCodeUseReqDTO);
        }
//        else  {
//            throw exception(NOT_SMS_CODE);
//        }
        // 用户账号注册
        MemberUserDO user = memberUserService.createUserByBusiness(createReqVO.getId(), createReqVO.getMobile(), createReqVO.getNickName(),
                createReqVO.getName(), getClientIP(), getTerminal(), createReqVO.getPassword(),createReqVO.getAreaId());

        int result =0;
        if(createReqVO.getId()!=null && createReqVO.getId()>0) {
            //商家信息修改
            BusinessUserDO bean = BeanUtils.toBean(createReqVO, BusinessUserDO.class);
            BusinessUserDO businessUserDO = businessUserMapper.getUserByUserId(createReqVO.getId());
            if (businessUserDO != null) {
                bean.setId(businessUserDO.getId());
                result = businessUserMapper.updateById(bean);
            } else {
                throw exception(USER_NOT_EXISTS);
            }
        }
        else if(user!=null &&user.getId()>0) {
            //创建商家信息(酒类模块商家表)
            BusinessUserDO businessUserDTO = BeanUtils.toBean(createReqVO, BusinessUserDO.class);
            businessUserDTO.setUserId(user.getId());
            businessUserDTO.setMemberTypeId(0L);
            //入驻商家--1,认证商家--2,商家团长--3,个人团长--4，保证金用户--5
            businessUserDTO.setCreditId(1);
            businessUserDTO.setCreditScore(Integer.parseInt(creditScore));
            //商家有发布功能，默认设置发布数量
            businessUserDTO.setBuyNum(Integer.parseInt(businessDefaultNumber));
            businessUserDTO.setComplainNum(Integer.parseInt(businessDefaultNumber));
            businessUserDTO.setSupplyNum(Integer.parseInt(businessDefaultNumber));
            businessUserDTO.setLeaveNum(Integer.parseInt(businessDefaultNumber));

            businessUserDTO.setStatus(BusinessUserEnum.APPLYING_STATUS.getCode());
            businessUserDTO.setIsAuth(BusinessUserEnum.UNVERIFIED_AUTH.getCode());
            businessUserDTO.setIsSelfSupport(BusinessUserEnum.NOT_SELF_SUPPORT.getCode());
            businessUserDTO.setIsOpen(0);

            //如果开启免费，则增加免费使用时间
            WineConfigDTO wineConfigDTO = wineConfigApi.getWineConfigInfo();
            if (wineConfigDTO != null && wineConfigDTO.getIsOpenMonth() > 0 && wineConfigDTO.getFreeMonth() > 0) {
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime expirationTime = now.plusMonths(wineConfigDTO.getFreeMonth());
                businessUserDTO.setExpirationTime(expirationTime);
            }
            result = businessUserMapper.insert(businessUserDTO);

            //添加商家佣金账户
            BrokerageUserDTO exitDTO = brokerageUserApi.getInfoByUserId(user.getId());
            if(exitDTO == null) {
                Long referrerId = 0L;
                LocalDateTime now = LocalDateTime.now();
                BrokerageUserDTO dto = new BrokerageUserDTO();

                dto.setId(user.getId());
                dto.setBindUserId(referrerId);
                dto.setBrokerageEnabled(false);

                dto.setBusinessType(0);
                dto.setUserBusiness(0);
                dto.setBusinessStartTime(now);
                dto.setBusinessEndTime(now);

                dto.setTeamType(0);
                dto.setUserTeam(0);
                dto.setTeamStartTime(now);
                dto.setTeamEndTime(now);

                //如果引荐人字段不为空  需要保存上下级关系
                if (createReqVO.getReferrerId() != null) {
                    referrerId = createReqVO.getReferrerId();
                } else {
                    //如果推荐手机号码不为空则保存上下级关系
                    if (!StringUtils.isEmpty(createReqVO.getIntroducerMobile())) {
                        MemberUserDO userByMobile = memberUserService.getUserByMobile(createReqVO.getIntroducerMobile());
                        if (userByMobile == null) {
                            throw exception(BROKERAGE_USER_NOT_EXISTS);
                        }
                        if (userByMobile.getId().equals(user.getId())) {
                            throw exception(BROKERAGE_BIND_SELF);
                        }
                        referrerId = userByMobile.getId();
                    }
                }

                if (referrerId > 0) {

                    dto.setBindUserId(referrerId);

                    //原来按上级过期计算，现修改成默认一年，这里就不赋值，在用户认证VIP的时候处理
//                MemberUserDO memberUserDO = memberUserService.getUser(referrerId);
//                if (memberUserDO != null) {
//                    if (memberUserDO.getIsBusiness() == 1) {
//                        //上级商家没有过期
//                        BusinessUserDO parBusinessDTO = businessUserMapper.getUserByUserId(referrerId);
//                        if (parBusinessDTO.getOverTime().isAfter(now) && parBusinessDTO.getIsAuth() == 1) {
//                            dto.setUserBusiness(1);
//                            dto.setBusinessEndTime(parBusinessDTO.getOverTime());
//                        }
//                    }
//                    if (memberUserDO.getIsTeam() == 1 && memberUserDO.getTeamAudit() == 2) {
//                        //上级团长没有过期
//                        if (memberUserDO.getTeamOverTime().isAfter(now)) {
//                            dto.setUserTeam(1);
//                            dto.setTeamEndTime(memberUserDO.getTeamOverTime());
//                        }
//                    }
//                }
                }

                brokerageUserApi.addBrokerageUser(dto);
            }

        }

        return result;
    }

    /**
     * 修改商家
     * @param createReqVO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer appUpdateBusinessUser(AppBusinessUserUpdateReqVO createReqVO) {
        Long userId = createReqVO.getUserId();
        MemberUserDO user = memberUserService.getUser(userId);
        if(user==null){
            throw exception(USER_NOT_EXISTS);
        }

        if (createReqVO.getAreaId()>0){
            user.setAreaId(createReqVO.getAreaId());
        }
        if (!StringUtils.isEmpty(createReqVO.getNickName())){
            user.setNickname(createReqVO.getNickName());
        }
        if (!StringUtils.isEmpty(createReqVO.getName())){
            user.setName(createReqVO.getName());
        }
        if (!StringUtils.isEmpty(createReqVO.getMobile())){
            user.setMobile(createReqVO.getMobile());
        }
        if (!StringUtils.isEmpty(createReqVO.getMoneyReceivingCode())){
            user.setMoneyReceivingCode(createReqVO.getMoneyReceivingCode());
        }
        //user.setPassword(null);
        //memberUserService.updateUser(BeanUtils.toBean(user, MemberUserUpdateReqVO.class));
        MemberUserDO ubean = BeanUtils.toBean(user, MemberUserDO.class);
        memberUserMapper.updateById(ubean);

        //商家信息修改
        BusinessUserDO bean = BeanUtils.toBean(createReqVO, BusinessUserDO.class);
        BusinessUserDO businessUserDO = businessUserMapper.getUserByUserId(userId);
        bean.setId(businessUserDO.getId());
        return businessUserMapper.updateById(bean);
    }

    /**
     * 前端个人团长申请,并可绑定上下级关系
     * @param createReqVO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer appCreateBusinessUserTeam(AppBusinessUserSaveReqVO createReqVO) {

        // 校验验证码
//        Integer scene = SmsSceneEnum.MEMBER_LOGIN.getScene();
//        SmsCodeUseReqDTO smsCodeUseReqDTO = new SmsCodeUseReqDTO();
//        smsCodeUseReqDTO.setCode(createReqVO.getCode());
//        smsCodeUseReqDTO.setMobile(createReqVO.getMobile());
//        smsCodeUseReqDTO.setUsedIp(getClientIP());
//        smsCodeUseReqDTO.setScene(scene);
//        smsCodeApi.useSmsCode(smsCodeUseReqDTO);

        // 用户账号注册
        MemberUserDO user = memberUserService.createUserByBusinessTeam(createReqVO.getId(), createReqVO.getMobile(), createReqVO.getNickName(),
                createReqVO.getName(), getClientIP(), getTerminal(), createReqVO.getPassword(), createReqVO.getAreaId(),
                createReqVO.getWechatNumber(), createReqVO.getMoneyReceivingCode(),createReqVO.getMark());

        int result =0;
        if(createReqVO.getId()!=null && createReqVO.getId()>0){
            //商家信息修改
            BusinessUserDO bean = BeanUtils.toBean(createReqVO, BusinessUserDO.class);
            BusinessUserDO businessUserDO = businessUserMapper.getUserByUserId(createReqVO.getId());
            if(businessUserDO!=null) {
                bean.setId(businessUserDO.getId());
                result = businessUserMapper.updateById(bean);
            }
            else {
                throw exception(USER_NOT_EXISTS);
            }
        }
        else if(user!=null &&user.getId()>0) {
            //创建商家信息(酒类模块商家表)
            BusinessUserDO businessUserDTO = BeanUtils.toBean(createReqVO, BusinessUserDO.class);
            businessUserDTO.setUserId(user.getId());
            businessUserDTO.setCreditScore(0);
            businessUserDTO.setBuyNum(0);
            businessUserDTO.setComplainNum(0);
            businessUserDTO.setSupplyNum(0);
            businessUserDTO.setLeaveNum(0);
            businessUserDTO.setStatus(BusinessUserEnum.APPLYING_STATUS.getCode());
            businessUserDTO.setIsAuth(BusinessUserEnum.UNVERIFIED_AUTH.getCode());
            businessUserDTO.setIsSelfSupport(BusinessUserEnum.NOT_SELF_SUPPORT.getCode());
            businessUserDTO.setIsOpen(0);
            //入驻商家--1,认证商家--2,商家团长--3,个人团长--4，保证金用户--5
            businessUserDTO.setCreditId(4);

            //如果开启免费，则增加免费使用时间
            WineConfigDTO wineConfigDTO = wineConfigApi.getWineConfigInfo();
            if (wineConfigDTO != null && wineConfigDTO.getIsOpenMonth() > 0 && wineConfigDTO.getFreeMonth() > 0) {
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime expirationTime = now.plusMonths(wineConfigDTO.getFreeMonth());
                businessUserDTO.setExpirationTime(expirationTime);
            }
            result = businessUserMapper.insert(businessUserDTO);

            //添加团长佣金账户
            BrokerageUserDTO exitDTO = brokerageUserApi.getInfoByUserId(user.getId());
            if (exitDTO == null) {
                Long referrerId = 0L;
                LocalDateTime now = LocalDateTime.now();
                BrokerageUserDTO dto = new BrokerageUserDTO();
                dto.setId(user.getId());
                dto.setBindUserId(referrerId);

                dto.setBrokerageEnabled(false);
                dto.setBusinessType(0);
                dto.setUserBusiness(0);
                dto.setBusinessStartTime(now);
                dto.setBusinessEndTime(now);

                dto.setTeamType(0);
                dto.setUserTeam(0);
                dto.setTeamStartTime(now);
                dto.setTeamEndTime(now);

                //如果引荐人字段不为空  需要保存上下级关系
                if (!StringUtils.isEmpty(createReqVO.getIntroducerMobile())) {
                    MemberUserDO userByMobile = memberUserService.getUserByMobile(createReqVO.getIntroducerMobile());
                    if (userByMobile == null) {
                        throw exception(BROKERAGE_USER_NOT_EXISTS);
                    }
                    if (userByMobile.getId().equals(user.getId())) {
                        throw exception(BROKERAGE_BIND_SELF);
                    }
                    referrerId = userByMobile.getId();

                    dto.setBindUserId(referrerId);

                    if (userByMobile.getIsBusiness() == 1) {
                        //上级商家没有过期
                        BusinessUserDO parBusinessDTO = businessUserMapper.getUserByUserId(referrerId);
                        if (parBusinessDTO.getOverTime().isAfter(now) && parBusinessDTO.getIsAuth() == 1) {
                            dto.setUserBusiness(1);
                            dto.setBusinessEndTime(parBusinessDTO.getOverTime());
                        }
                    }
                    if (userByMobile.getIsTeam() == 1 && userByMobile.getTeamAudit() == 2) {
                        //上级团长没有过期
                        if (userByMobile.getTeamOverTime().isAfter(now)) {
                            dto.setUserTeam(1);
                            dto.setTeamEndTime(userByMobile.getTeamOverTime());
                        }
                    }
                }
                brokerageUserApi.addBrokerageUser(dto);
            }
        }

        return result;
    }

    /**
     * 查询团长下面的商家（列表）
     * @param type
     * @return
     */
    @Override
    public List<AppBusinessUserRespVO> appGetBusinessUserList(Integer type) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();

        List<Long> userIdList = brokerageUserApi.getUserIdList(loginUserId);

//        List<AppBusinessUserRespVO> appBusinessUserRespVOS = businessUserMapper.selectJoinList(AppBusinessUserRespVO.class, new MPJLambdaWrapperX<BusinessUserDO>()
//                .inIfPresent(BusinessUserDO::getUserId, userIdList));
//
//        System.out.println("商家列表" + appBusinessUserRespVOS);
//        System.out.println("商家列表" + appBusinessUserRespVOS.size());

        if (CollectionUtil.isEmpty(userIdList)){
            return null;
        }

        MPJLambdaWrapperX<BusinessUserDO> wrapperX = new MPJLambdaWrapperX<BusinessUserDO>();

        wrapperX.inIfPresent(BusinessUserDO::getUserId, userIdList)
                .leftJoin(MemberUserDO.class, MemberUserDO::getId, BusinessUserDO::getUserId)
                .leftJoin(MemberDeadlineDO.class, MemberDeadlineDO::getUserId, MemberUserDO::getId)
                .selectAll(BusinessUserDO.class)

                .selectAs(MemberDeadlineDO::getStartDate, AppBusinessUserRespVO::getOpenTime)
                .selectAs(MemberDeadlineDO::getEndDate, AppBusinessUserRespVO::getOverTime)

                .selectAs(MemberUserDO::getAvatar, AppBusinessUserRespVO::getAvatar)
                .selectAs(MemberUserDO::getNickname, AppBusinessUserRespVO::getNickname);
        if (type!=null) {
            if (type == 0) {
                wrapperX.isNull(BusinessUserDO::getOpenTime);
                wrapperX.orderByDesc(BusinessUserDO::getCreateTime);
            } else {
                wrapperX.isNotNull(BusinessUserDO::getOpenTime);
                wrapperX.isNotNull(BusinessUserDO::getOverTime);
                wrapperX.orderByAsc(BusinessUserDO::getOverTime);
            }
        }

        return businessUserMapper.selectJoinList(AppBusinessUserRespVO.class, wrapperX);

//        return businessUserMapper.selectJoinList(AppBusinessUserRespVO.class, new MPJLambdaWrapperX<BusinessUserDO>()
//                .inIfPresent(BusinessUserDO::getUserId, userIdList)
//                .leftJoin(MemberUserDO.class, MemberUserDO::getId, BusinessUserDO::getUserId)
//                .leftJoin(MemberDeadlineDO.class, MemberDeadlineDO::getUserId, MemberUserDO::getId)
//                .selectAll(BusinessUserDO.class)
//                .selectAs(MemberDeadlineDO::getStartDate, AppBusinessUserRespVO::getOpenTime)
//                .selectAs(MemberDeadlineDO::getEndDate, AppBusinessUserRespVO::getOverTime)
//                .selectAs(MemberUserDO::getAvatar, AppBusinessUserRespVO::getAvatar)
//                .selectAs(MemberUserDO::getNickname, AppBusinessUserRespVO::getNickname));
    }


    @Override
    public AppUserAddressRespVO appGetBusinessUserByMobile(String mobile) {
        return businessUserMapper.getBusinessUserByMobile(mobile);
    }

    /**
     * 查询团长下面的商家收益信息
     * @param settlement
     * @return
     */
    @Override
    public List<AppBusinessUserRespVO> appGetBusinessUserEarningsList(Integer settlement) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        List<Long> userIdList = brokerageUserApi.getUserIdList(loginUserId);
        //已结算
        if (CollectionUtil.isEmpty(userIdList)){
            return null;
        }

        if (settlement.equals(1)) {
            return businessUserMapper.selectJoinList(AppBusinessUserRespVO.class, new MPJLambdaWrapperX<BusinessUserDO>()
                    .inIfPresent(BusinessUserDO::getUserId, userIdList)
                    .leftJoin(MemberUserDO.class, MemberUserDO::getId, BusinessUserDO::getUserId)
                    .leftJoin(MemberDeadlineDO.class, MemberDeadlineDO::getUserId, MemberUserDO::getId)
                    .leftJoin(MemberTypeDO.class, MemberTypeDO::getId, MemberDeadlineDO::getMemberTypeId)
                    .leftJoin(BrokerageUserDO.class, BrokerageUserDO::getId, MemberUserDO::getId)
                    .le(MemberDeadlineDO::getEndDate, LocalDateTime.now())
                    .ge(MemberDeadlineDO::getStartDate, LocalDateTime.now())
                    .selectAll(BusinessUserDO.class)
                    .selectAs(MemberDeadlineDO::getStartDate, AppBusinessUserRespVO::getOpenTime)
                    .selectAs(MemberDeadlineDO::getEndDate, AppBusinessUserRespVO::getExpirationTime)

                    .selectAs(MemberTypeDO::getTermType, AppBusinessUserRespVO::getTermType)

                    .selectAs(BrokerageUserDO::getBrokeragePrice, AppBusinessUserRespVO::getBrokeragePrice)

                    .selectAs(MemberUserDO::getAvatar, AppBusinessUserRespVO::getAvatar)
                    .selectAs(MemberUserDO::getNickname, AppBusinessUserRespVO::getNickname));
        } else {
            //未结算
            return businessUserMapper.selectJoinList(AppBusinessUserRespVO.class, new MPJLambdaWrapperX<BusinessUserDO>()
                    .inIfPresent(BusinessUserDO::getUserId, userIdList)
                    .leftJoin(MemberUserDO.class, MemberUserDO::getId, BusinessUserDO::getUserId)
                    .leftJoin(MemberDeadlineDO.class, MemberDeadlineDO::getUserId, MemberUserDO::getId)
                    .leftJoin(MemberTypeDO.class, MemberTypeDO::getId, MemberDeadlineDO::getMemberTypeId)
                    .leftJoin(BrokerageUserDO.class, BrokerageUserDO::getId, MemberUserDO::getId)
                    .le(MemberDeadlineDO::getEndDate, LocalDateTime.now())
                    .ge(MemberDeadlineDO::getStartDate, LocalDateTime.now())

                    .selectAll(BusinessUserDO.class)

                    .selectAs(MemberDeadlineDO::getStartDate, AppBusinessUserRespVO::getOpenTime)
                    .selectAs(MemberDeadlineDO::getEndDate, AppBusinessUserRespVO::getExpirationTime)

                    .selectAs(MemberTypeDO::getTermType, AppBusinessUserRespVO::getTermType)

                    .selectAs(BrokerageUserDO::getFrozenPrice, AppBusinessUserRespVO::getFrozenPrice)

                    .selectAs(MemberUserDO::getAvatar, AppBusinessUserRespVO::getAvatar)
                    .selectAs(MemberUserDO::getNickname, AppBusinessUserRespVO::getNickname));
        }

    }

    /**
     * 商家申请团长
     * @param createReqVO
     * @return
     */
    @Override
    public Integer appCreateBusinessUserTeamSimple(AppBusinessUserSaveReqVO createReqVO) {
        MemberUserDO user = memberUserService.createUserByBusinessTeamSimple(createReqVO.getMobile());
        return 1;
    }



    @Override
    public BusinessUserDTO register(BusinessUserDTO dto) {
        Long count = businessUserMapper.selectCount(new LambdaQueryWrapperX<BusinessUserDO>().eq(BusinessUserDO::getUserId, dto.getUserId()));
        if (!count.equals(0L)) {
            throw exception(BUSINESS_USER_EXISTS);
        }
        BusinessUserDO bean = BeanUtils.toBean(dto, BusinessUserDO.class);
        int insert = businessUserMapper.insert(bean);
        if (insert > 0) {
            return dto;
        } else {
            return null;
        }
    }

    @Override
    public void updateUserInfo(BusinessUserDTO updateReqVO) {
        // 校验存在
        validateBusinessUserExists(updateReqVO.getId());
        // 更新
        BusinessUserDO updateObj = BeanUtils.toBean(updateReqVO, BusinessUserDO.class);
        businessUserMapper.updateById(updateObj);
    }

    @Override
    public BusinessUserDTO getUserByUserId(Long userId) {
        BusinessUserDO businessUserDO = businessUserMapper.getUserByUserId(userId);
        BusinessUserDTO dto = BeanUtils.toBean(businessUserDO, BusinessUserDTO.class);
        return dto;
    }


    @Override
    public BusinessUserRespVO getBusinessUserInfo(Long userId) {

        BusinessUserRespVO businessUserRespVO = businessUserMapper.selectJoinOne(BusinessUserRespVO.class, new MPJLambdaWrapperX<BusinessUserDO>()
                .eq(BusinessUserDO::getUserId, userId)
                .leftJoin(BusinessCreditDO.class, BusinessCreditDO::getId, BusinessUserDO::getCreditId)
                .leftJoin(MemberTypeDO.class, MemberTypeDO::getId, BusinessUserDO::getMemberTypeId)
                .leftJoin(MemberUserDO.class, MemberUserDO::getId, BusinessUserDO::getUserId)
                .selectAll(BusinessUserDO.class)

                .selectAs(BusinessCreditDO::getId, BusinessUserRespVO::getCreditId)
                .selectAs(BusinessCreditDO::getName, BusinessUserRespVO::getCreditName)

                .selectAs(MemberTypeDO::getId, BusinessUserRespVO::getMemberTypeId)

                .selectAs(MemberUserDO::getMobile, BusinessUserRespVO::getMobile)
                .selectAs(MemberUserDO::getIsTeam, BusinessUserRespVO::getIsTeam)
                .selectAs(MemberUserDO::getIsBusiness, BusinessUserRespVO::getIsBusiness)
                .selectAs(MemberUserDO::getTeamAudit, BusinessUserRespVO::getTeamAudit)
                .selectAs(MemberUserDO::getNickname, BusinessUserRespVO::getNickname)
                .selectAs(MemberUserDO::getName, BusinessUserRespVO::getRealName)
                .selectAs(MemberUserDO::getMark, BusinessUserRespVO::getMark)
                .selectAs(MemberUserDO::getAvatar, BusinessUserRespVO::getAvatar)
                .selectAs(MemberUserDO::getMoneyReceivingCode, BusinessUserRespVO::getMoneyReceivingCode)
                .selectAs(MemberUserDO::getTeamOpenTime, BusinessUserRespVO::getTeamOpenTime)
                .selectAs(MemberUserDO::getTeamOverTime, BusinessUserRespVO::getTeamOverTime)
                .selectAs(MemberUserDO::getSex, BusinessUserRespVO::getSex)
                .selectAs(MemberUserDO::getLoginDate, BusinessUserRespVO::getLoginDate)
                .selectAs(MemberUserDO::getLoginIp, BusinessUserRespVO::getLoginIp)
        );
        return businessUserRespVO;
    }


    @Override
    public List<BusinessUserDTO> getBusinessUserList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        List<BusinessUserDO> businessUserDOList = businessUserMapper.getUserByUserIds(ids);
        return BeanUtils.toBean(businessUserDOList, BusinessUserDTO.class);
    }

}
